<?php
/**
 * Author:xsc
 * Time:2023/10/12 16:12
 */

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Exceptions\BusinessException;
use App\Common\ResponseCode;
use App\Service\Common\PlatformService;

class CheckPlatformMiddleware
{

    public function handle(Request $request, Closure $next)
    {
        $data = $request->input();

        //Log::info("[中间件]验证平台信息中间件:接收参数" . json_encode($data, 256));

        if (!$data) {
            throw new BusinessException(ResponseCode::PARAM_ILLEGAL, ['error' => '请求参数不能为空']);
        }

        if (!isset($data['access_mode']) || $data['access_mode'] != 'platform') {
            throw new BusinessException(ResponseCode::PARAM_ILLEGAL, ['error' => '请使用平台模式接入']);
        }

        if (!isset($data['timestamp']) || empty($data['timestamp'])) {
            throw new BusinessException(ResponseCode::PARAM_ILLEGAL, ['error' => '请求时间不能为空']);
        }

        if (!is_integer($data['timestamp'])) {
            throw new BusinessException(ResponseCode::PARAM_ILLEGAL, ['error' => '请求时间格式不正确']);
        }

        if (!isset($data['access_mid']) || empty($data['access_mid'])) {
            throw new BusinessException(ResponseCode::PARAM_ILLEGAL, ['error' => '接入平台号不能为空']);
        }

        // 平台信息
        $platform_no = $data['access_mid'];
        $platform_info = PlatformService::getInstance()->getInfoWithCache($platform_no);

        if (!$platform_info) {
            throw new BusinessException(ResponseCode::PARAM_ILLEGAL, ['error' => '平台不存在']);
        }

        if (!$platform_info['public_key']) {
            throw new BusinessException(ResponseCode::PARAM_ILLEGAL, ['error' => '平台未配置必要信息']);
        }

        // 校验平台的路由权限
        $route_name = trim($request->getPathInfo(), '/');
        $check = PlatformService::getInstance()->checkPlatformRoute($platform_info['id'], $route_name);
        if (!$check) {
            throw new BusinessException(ResponseCode::PARAM_ILLEGAL, ['error' => '暂无接口权限']);
        }

        return $next($request);
    }

}
